const modules = import.meta.glob(["pkgs/cmpnts/*/*.js"], { eager: true });
import _ from "lodash";
import { cloneCmpnt } from "./clone";
let cmpnts = {
  containers: {},
  widgets: {},
  pages: {},
  All: {},
  find: function (name) {
    const formattedName = _.upperFirst(_.camelCase(name));
    const result = this.All[formattedName];
    if (result === undefined) throw new Error(`未找到组件'${name}' `);
    return result;
  },
  finds: function (name) {
    return [this.find(name)];
  },
};
for (const fullPath in modules) {
  const lastName = _.last(fullPath.split("/"));
  if (lastName.startsWith("_")) {
    continue;
  }
  const module = modules[fullPath].default || modules[fullPath];
  for (const name in module) {
    let md = module[name];
    let cmpntName = _.upperFirst(_.camelCase(name));
    let cmpntModule = bindAttr(md);
    validPropery(cmpntModule, fullPath);
    if (fullPath.indexOf("container") > -1) {
      cmpntModule.catgory = "containers";
      cmpnts.containers[cmpntName] = cmpntModule;
    } else if (fullPath.indexOf("widget") > -1) {
      cmpntModule.catgory = "widgets";
      cmpnts.widgets[cmpntName] = cmpntModule;
    } else if (fullPath.indexOf("page") > -1) {
      cmpntModule.catgory = "pages";
      cmpnts.pages[cmpntName] = cmpntModule;
    }
    cmpnts.All[cmpntName] = cmpntModule;
  }
}
function bindAttr(obj) {
  let nobj = cloneCmpnt(obj);
  nobj.clone = function () {
    return cloneCmpnt(this);
  };
  return nobj;
}

// 检查对象中是否缺少必要的属性
function validPropery(obj, fullPath) {
  const requiredProperties = ["cmpnt", "props"];
  for (const prop of requiredProperties) {
    if (!(prop in obj)) {
      throw new Error(`对象:${JSON.stringify(obj)} ${fullPath}缺少属性${prop}`);
    }
  }

  // 如果有 children 属性，则递归检查每个子对象
  if (Array.isArray(obj.children)) {
    for (const child of obj.children) {
      validPropery(child);
    }
  }

  // 如果所有检查都通过，则返回 true
  return true;
}
export default cmpnts;
